<template>
  <el-affix :offset="0" class="top">
    <div class="header">
      <div style="flex:2;font-family:'幼圆';font-size: 3vw;text-align: center;">独白时光</div>
      <div style="flex:3;display:flex;justify-content: s;">
        <div :class="{ 'isColor': isactive == item.id }" class="test" @click="choice(item.id)"
          style="width:100%;height:100%;display:flex;align-items: center;" v-for="item in MentList" :key="item.id">
          <img :src="item.icon" alt="" style="height:20%;width:20%;margin-right: 0.5vw">
          <span :class="{ isColor: isactive === item.id }" style="font-size:1vw;">{{ item.title }}</span>
        </div>
      </div>
      <div style="flex:2;display: flex;justify-content:center;align-items: center;">
        <div v-if="(isadmin.role == '1' || !isadmin.role)"
          style="flex:2;display: flex;justify-content:center;align-items: center;">
          <div @click="login" style="margin-right: 1vw;font-weight: bold;font-size: 1.3vw;z-index: 999;"> {{
            choose_login ?
              '退出' : '未登录' }}</div>








          <el-upload :disabled="!choose_login" class="upload-demo" :action="base_url + '/admin/users/upload'"
            :show-file-list="false" :before-upload="bofore_upload" :on-success="on_success">
            <el-avatar style="width: 4vw;height: 4vw;" icon="el-icon-user-solid" size="large" shape="circle"
              :src="base_url + connment_user.avatar" fit="fill"></el-avatar>
          </el-upload>
          <span v-if="choose_login" style="font-size: 0.8vw;margin-left: 0.5vw;">点击更换头像</span>










        </div>
        <div v-else>
          <el-avatar style="width: 4vw;height: 4vw;" icon="el-icon-user-solid" size="large" shape="circle"
            :src="base_url + isadmin.avatar" fit="fill"></el-avatar>
        </div>
      </div>
    </div>
  </el-affix>
  <el-dialog style="background-color: rgba(255,255,255,0.5);" v-model="dialogFormVisible" :title="isLogin ? '登录' : '注册'"
    width="500">
    <el-form :model="form">
      <el-form-item label="用户名" :label-width="formLabelWidth">
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" :label-width="formLabelWidth">
        <el-input v-model="form.password" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="display: flex;justify-content: center;align-items: center;">
        <el-button type="primary" @click="to_login">{{ isLogin ? "登录" : "注册" }}</el-button>
        <div @click="cut" style="color:orange;font-weight: bold;margin-left: 1vw;text-shadow: 0 0 10px black;">{{
          isLogin ?
            "没有账号?去注册"
            : "已有帐号，登录" }}</div>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router'
import CommonStore from "@/store/CommonStore"
import { ElMessage } from 'element-plus';
import { Admin_info, user_info } from "@/utils/Local"
import { AppStore } from "@/store/index"
import { loginuser } from '@/apis/web/WebApi';
import { type User_info } from '@/types/Admin';
import { update_avatar } from "@/apis/CommonUserApi"
const base_url = import.meta.env.VITE_APP_URL
const Apps = AppStore()
const user_avatar = ref('')
//判断上传的是否为图片
const regex = /^image\//;
let isactive = ref('')
onMounted(() => {
  const result = user_info.Get_info()
  if (result._id) {
    choose_login.value = true
  }
  Object.assign(connment_user, result)
  Object.assign(isadmin, Admin_info.Get_info())
})
watch(() => Apps.isadmin, () => {
  if (Apps.isadmin) {
    Object.assign(isadmin, Admin_info.Get_info())
  } else {
    choose_login.value = false
    Object.assign(isadmin, {
      avatar: "",
      bilibili: '',
      csdn: "",
      english_name: "",
      famous_sentence: "",
      gitee: "",
      introduce: "",
      qq: "",
      role: "",
      school: "",
      tags: [],
      username: "",
      _id: ""

    })
  }
})
const store = CommonStore()
const isadmin = reactive<any>({
  avatar: "",
  bilibili: '',
  csdn: "",
  english_name: "",
  famous_sentence: "",
  gitee: "",
  introduce: "",
  qq: "",
  role: "",
  school: "",
  tags: [],
  username: "",
  _id: ""

})
//判断是否登陆过
const choose_login = ref(false)
const connment_user = reactive<User_info>({
  avatar: '',
  role: '',
  username: '',
  _id: ''
})
let isLogin = ref(true)
const form = reactive({
  username: "",
  password: ""
})
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const router = useRouter()
const choice = (value: string) => {
  isactive.value = value
  switch (value) {
    case '0':
      router.push('/')
      break;
    case '1':
      router.push('/albums')
      break;
    case "2":
      router.push('/speak')
      break;
    case '3':
      router.push('/message')
      break;
    case '4':
      router.push("/user")
      break;
    case '5':
      router.push('/login')
      break;
    default:
      break;
  }
}
const MentList = [
  {
    id: '0',
    title: "首页",
    icon: base_url + '/assets/svg/home.svg'
  },
  {
    id: "1",
    title: "相册",
    icon: base_url + '/assets/svg/ablums.svg'
  },
  {
    id: "2",
    title: "说说",
    icon: base_url + '/assets/svg/Message.svg'
  },
  {
    id: '3',
    title: "留言",
    icon: base_url + '/assets/svg/speak.svg'
  },
  {
    id: '4',
    title: '个人中心',
    icon: base_url + '/assets/svg/user.svg'

  },
  {
    id: "5",
    title: "后台",
    icon: base_url + '/assets/svg/pay_manger.svg'

  }
]
const login = () => {
  const islogin = user_info.Get_info()
  if (islogin._id) {
    user_info.Re_move()
    choose_login.value = false
    Object.assign(connment_user, {
      avatar: '',
      role: '',
      username: '',
      _id: ''
    })
  } else {
    dialogFormVisible.value = true
  }

}
const to_login = async () => {
  if (form.password.trim() == "" || form.username.trim() == "") {
    ElMessage({
      type: "error",
      message: "输入内容不能为空"
    })
    return
  }
  if (form.password.trim().length < 6 || form.username.trim().length < 2 || form.username.trim().length > 10) {
    ElMessage({
      type: "error",
      message: "用户名2-10位，密码最小6位"
    })
    return
  }
  if (!isLogin.value) {
    try {

      await store.register(form)

      ElMessage({
        type: "success",
        message: "注册成功"
      })
      Object.assign(form, {
        username: "",
        password: ""
      })
      dialogFormVisible.value = false
    } catch (error) {

    }

  } else {
    const result: any = await loginuser(form)
    user_info.Set_info(result.data)
    user_info.Set_token(result.token)
    Object.assign(connment_user, result.data)
    choose_login.value = true
    if (result.code === 200) {
      ElMessage({
        type: "success",
        message: "登录成功"
      })
      dialogFormVisible.value = false
      console.log(result)
    } else {

    }
    Object.assign(form, {
      username: "",
      password: ""
    })
    console.log("登录")
  }

}
const cut = () => {
  isLogin.value = !isLogin.value
  Object.assign(form, {
    username: "",
    password: ""
  })
}
//上传前
const bofore_upload = (e: any) => {
  // console.log("???", regex.test(e.type), e)
  if (regex.test(e.type)) {


  } else {
    console.log("错误格式")
    ElMessage({
      type: "error",
      message: "请上传正确的图片格式"
    })

    return false

  }
}
const on_success = (e: any) => {
  if (e.code === 200) {
    user_avatar.value = e.data.avatar

    ElMessage({
      type: "success",
      message: "上传成功"
    })
    const result = user_info.Get_info()
    result.avatar = user_avatar.value
    user_info.Set_info(result)
    connment_user.avatar = user_avatar.value
    update_avatar({ id: result._id, url: user_avatar.value })
    console.log(user_avatar.value, 'fsds')

  }
}
</script>
<style scoped lang="scss">
.affix-container {
  text-align: center;
  height: 15vh;
  border-radius: 4px;
}

.header {
  background-color: transparent;
  width: 100%;
  height: 10vh;
  transition: background-color 1s;
  display: flex;
  justify-content: space-around;
  align-items: center;
  color: white;
  font-weight: bold;

  .test:hover {
    color: orange
  }
}

.header:hover {
  background-color: rgba(0, 0, 0, 0.5);

}

.isColor {
  color: orange;
}
</style>